<style>
    #railway-update {
        padding: 20px 25px 0px 0;
    }

    #railway-update .layui-form-label {
        width: 88px;
    }

    #railway-update .layui-input-block {
        margin-left: 120px;
    }
    #railway-update .layui-textarea{
        min-height: 95px;
    }
    #railway-getSegwords .layui-textarea{
        min-height: 34px;
    }
    #railway-getSegwords{
        padding: 0px 25px 0px 0;
    }

    #railway-getSegwords .layui-form-label {
        width: 88px;
    }

    #railway-getSegwords .layui-input-block {
        margin-left: 120px;
    }
    #operateButtonGroup .layui-btn-sm{
        font-size:14px;
    }
    #operateButtonGroup .layui-btn{
        background-color: #2F4056;
    }
</style>
<style>


    .tag:not(body) {
        align-items: center;
        background-color: #f5f5f5;
        border-radius: 4px;
        color: #4a4a4a;
        display: inline-flex;
        /*! font-size:.75rem; */
        height: 2em;
        justify-content: center;
        line-height: 1.5;
        padding-left: .75em;
        padding-right: .75em;
        white-space: nowrap
    }

    a.tagfirst {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
        cursor: pointer;
    }

    span.tag {
        margin-left: -5px;
        margin-right: 5px;
        border-bottom-left-radius: 0;
        border-top-left-radius: 0
    }

    .layui-icon {

        cursor: pointer;

    }

    .layui-icon:hover {

        color: #5a8bff;
    }
</style>
<div class="layui-fluid" id="railway-update">
    <form class="layui-form" action="" lay-filter="railway-update-form">
        <div class="layui-form-item febs-hide">
            <label class="layui-form-label febs-form-item-require">id：</label>
            <div class="layui-input-block">
                <input type="text" name="railwayId" class="layui-input">
            </div>
        </div>
       
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">原始文本：</label>
            <div class="layui-input-block">
                <textarea name="originContent" maxlength="500" class="layui-textarea" disabled></textarea>
            </div>
        </div>
        <div class="layui-form-item febs-hide">
            <button class="layui-btn" lay-submit="" lay-filter="railway-update-form-submit" id="submit"></button>
            <button type="reset" class="layui-btn" id="reset"></button>
            <!--   Railway的其他属性，都隐藏，然后底下的button按下时设置这个属性的值         -->
            <input type="text" name="isSeg">
            <input type="text" name="segWords">
            <input type="text" name="segWordsHtml">
        </div>
    </form>
</div>
<div class="layui-fluid" id="railway-getSegwords">
    <form class="layui-form" action="" lay-filter="railway-getSegwords-form">


        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">
<!--                分词操作：-->
            </label>
            <div class="layui-input-block" id="operateButtonGroup">
<!--                <div class="layui-btn-group" >-->
<!--                    <button class="layui-btn layui-btn-sm" lay-submit="" lay-filter="railway-getSegwords-form-submit" id="getSegwordsubmit" >获取自动分词结果</button>-->

<!--                </div>-->
                <div class="layui-btn-group">
                    <a id="railwaySpecial" class="layui-btn layui-btn-sm" style="background-color: #5FB878;" >
                        标记为铁路专有词Railway
                    </a>
                </div>
                <div class="layui-btn-group" >
<!--                    <button class="layui-btn layui-btn-sm" lay-submit="" lay-filter="railway-operateSegwords-form-submit" id="operateSegwordsubmit">操作说明</button>-->
<!--                    <span class="layui-icon layui-icon-question-circle" lay-filter="railway-operateSegwords-form-submit" style="font-size: 30px;"></span>-->


                            <span id="segHelpIcon" class="layui-icon layui-icon-question-circle" style="font-size: 30px;"></span>



                </div>
            </div>
        </div>
<!--        <div class="layui-form-item layui-form-text">-->
<!--            <label class="layui-form-label">-->
<!--&lt;!&ndash;                标记操作：&ndash;&gt;-->
<!--            </label>-->
<!--            <div class="layui-input-block">-->
<!--                <div>-->
<!--                    <a id="railwaySpecial" class="tag is-medium tagfirst"-->
<!--                       style="color: rgb(255, 255, 255); background-color: rgb(255, 0, 0);">-->
<!--                        铁路专有词-->
<!--                    </a>-->
<!--                    <span class="tag is-medium">r</span>-->
<!--&lt;!&ndash;                    <a class="tag is-medium tagfirst" style="color: rgb(255, 255, 255); background-color: rgb(51, 204, 153);">&ndash;&gt;-->
<!--&lt;!&ndash;                        E1实体&ndash;&gt;-->
<!--&lt;!&ndash;                    </a> <span class="tag is-medium">e1</span>&ndash;&gt;-->
<!--&lt;!&ndash;                    <a class="tag is-medium tagfirst" style="color: rgb(255, 255, 255); background-color: rgb(255, 204, 0);">&ndash;&gt;-->
<!--&lt;!&ndash;                        E2实体&ndash;&gt;-->
<!--&lt;!&ndash;                    </a> <span class="tag is-medium">e2</span>&ndash;&gt;-->
<!--                </div>-->
<!--            </div>-->
<!--        </div>-->
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">分词结果：</label>
            <div class="layui-input-block">
<!--                <textarea name="jiebaResult" maxlength="200" class="layui-textarea" disabled></textarea>-->
                <!-- 加载编辑器的容器 -->

                <script id="container" name="content" type="text/plain" style="height:200px;">
                </script>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">铁路专有词：</label>
            <div class="layui-input-block">
                <textarea id="railwaySpecialWords" name="railwaySpecialWords" maxlength="200" class="layui-textarea" disabled></textarea>
            </div>
        </div>
    </form>
</div>
<script th:src="@{ueditor/ueditor.config.js}"></script>
<script th:src="@{ueditor/ueditor.all.js}"></script>
<script data-th-inline="javascript">
    layui.use(['jquery', 'febs', 'form', 'validate'], function () {
        var $ = layui.jquery,
            febs = layui.febs,
            form = layui.form,
            railway = [[${railway}]],
            $view = $('#railway-update'),
            validate = layui.validate;
        var railwaySpecialWords="";
        form.verify(validate);
        form.render();

        initrailwayValue();

        function initrailwayValue() {
            form.val("railway-update-form", {
                "railwayId": railway.railwayId,
                "originContent": railway.originContent,
                "isSeg":railway.isSeg,
                "segWords":railway.segWords,
                "segWordsHtml":railway.segWordsHtml
            });
        }
        function setRailwaySpecialWords(e){
            railwaySpecialWords="";

            $(e.body).find("span").each(function(index,element){

                //alert($(element).text());
                railwaySpecialWords=railwaySpecialWords+$(element).text()+",";
            });

            $("#railwaySpecialWords").text(railwaySpecialWords);
        }
        form.on('submit(railway-update-form-submit)', function (data) {
            //编辑器内容不为空，说明进行了分词
            if(ue.getContentTxt()!=""){
                data.field.isSeg="1";
                data.field.segWords=ue.getContentTxt();
                ueHtml=ue.getContent();
                data.field.segWordsHtml=ueHtml.substr(3,ueHtml.length-7);
                //把标记的铁路专有词汇添加到数据字典中
                febs.post(ctx + 'dataDictionary/addContents/'+railwaySpecialWords, null, function () {

                });
            }
            debugger;
            if (febs.nativeEqual(data.field, railway)) {
                febs.alert.warn('数据未作任何修改！');
                return false;
            }

            febs.post(ctx + 'railway/updateSeg', data.field, function () {
                layer.closeAll();
                febs.alert.success('修改成功');
                $('#febs-railway').find('#query').click();
            });
            return false;
        });

        form.on('submit(railway-getSegwords-form-submit)', function (data) {
            febs.post(ctx + 'railway/getJiebaResult', {originContent:railway.originContent},function (res) {
                ue.setContent(res.data);
                febs.alert.success('获取电脑分词结果成功！');
            });
            railwaySpecialWords="";
            $("#railwaySpecialWords").text("");
            return false;
        });

        $('#segHelpIcon').on("click", function () {
            febs.modal.open('操作说明', 'mark/railway/operateSegwords', {
                area: $(window).width() <= 750 ? '90%' : '70%',
                btn2: function () {
                    layer.closeAll();
                }
            });
        });



        //比较两个字符串是否只相差一个空格
        function compareTwoString(shortString, longString) {
            //若shortString的length更长，交换shortStirng和longString
            if (shortString.length > longString.length) {
                tempString = shortString;
                shortString = longString;
                longString = tempString;
            }
            var differentChar;
            for (i = 0; i < longString.length; i++) {
                if (shortString.charAt(i) == longString.charAt(i)) {
                    continue;
                } else {
                    differentChar = longString.charAt(i);
                    //alert(differentChar);
                    //console.log((differentChar));
                    //不一样的字符是否是空格
                    return differentChar == " " ? true : false;
                }
            }
            // if(i=shortString.length){
            //     differentChar=longString.charAt(longString.length);
            //     alert(differentChar);
            //     //不一样的字符是否是空格
            //     return differentChar==" "?true:false;
            // }
        }

        UE.registerUI('railwayspecial', function (editor, uiName) {
            //注册按钮执行时的command命令，使用命令默认就会带有回退操作
            editor.registerCommand(uiName, {
                execCommand: function () {
                    //alert('execCommand:' + uiName);
                    //var te=editor.selection.getText();
                    //alert(te);
                    editor.execCommand('forecolor', '#FFFFFF'); //设置字体颜色
                    editor.execCommand('backcolor', '#5FB878'); //设置字体背景颜色
                    var spanNode = editor.selection.getStart();
                    spanNode.innerHTML = spanNode.innerHTML + "<a class='delete'></a>";
                    setRailwaySpecialWords(editor);
                    //alert(te);
                    editor.selection.clearRange();
                }
            });
            //创建一个button
            var btn = new UE.ui.Button({
                //按钮的名字
                name: uiName,
                //提示
                title: uiName,
                //添加额外样式，指定icon图标，这里默认使用一个重复的icon
                cssRules: 'background-position: -500px 0;',
                //点击时执行的命令
                onclick: function () {
                    //这里可以不用执行命令,做你自己的操作也可
                    editor.execCommand(uiName);
                }
            });
            //没有toolbar了，所以要去掉按钮的状态反射
            //当点到编辑内容上时，按钮要做的状态反射
            // editor.addListener('selectionchange', function () {
            //     //var te=editor.selection.getText();
            //     //alert(te);
            //     var state = editor.queryCommandState(uiName);
            //     if (state == -1) {
            //         btn.setDisabled(true);
            //         btn.setChecked(false);
            //     } else {
            //         btn.setDisabled(false);
            //         btn.setChecked(state);
            //     }
            // });
            //因为你是添加button,所以需要返回这个button
            return btn;
        });
        var ue = UE.getEditor('container', {
            toolbars: [
                []
            ],
            elementPathEnabled: false,
            wordCountMsg: false,
            wordCount: false,
            enableAutoSave: false,
            enableContextMenu: false
        });
        var backspaceChar = "";
        var selectedRange;
        var contentBeforeKeydown = "", contentAfterKeyup = "", contentBeforeKeydownHtml = "", contentAfterKeyupHtml = "";
        // ue.addListener('contentchange', function () {
        //     contentAfterKeyup=ue.getContentTxt();
        //     contentAfterKeyupHtml=ue.getContent();
        //     //alert("1:"+contentBeforeKeydown+"\n"+"2:"+contentAfterKeyup);
        //     if(!compareTwoString(contentAfterKeyup,contentBeforeKeydown)){
        //         ue.setContent2(contentBeforeKeydownHtml);
        //     };
        // });
        //对编辑器的操作最好在编辑器ready之后再做
        ue.ready(function () {

            //删除toolbar
            $("#edui1_toolbarbox").remove();
            //若校对过设置编辑器的内容为segWordsHtml，否则设置为结巴分词后的结果
            if(railway.isSeg=="1"){
                //初始化ue编辑器内容
                ue.setContent(railway.segWordsHtml);
                //初始化标记的铁路专有词
                setRailwaySpecialWords(ue);
            }
            else{
                //初始化ue编辑器内容
                ue.setContent(railway.segWordsJieba);
            }

            //获取html内容，返回: <p>hello</p>
            //var html = ue.getContent();
            //alert(html);
            //获取纯文本内容，返回: hello
            contentBeforeKeydown = ue.getContentTxt();
            $('#railwaySpecial').on("click", function () {
                ue.execCommand('railwayspecial');
            });
            ue.addshortcutkey("railwayspecial", "ctrl+82");
            //ue.focus();
            //selectedRange = ue.selection.getNative().getRangeAt(0);


            UE.dom.domUtils.on(ue.body, "keyup", function (oEvent) {
                var oEvent = oEvent || window.oEvent;
                //获取键盘的keyCode值
                var nKeyCode = oEvent.keyCode || oEvent.which || oEvent.charCode;
                contentAfterKeyup = ue.getContentTxt();
                contentAfterKeyupHtml = ue.getContent();
                //获取ctrl 键对应的事件属性
                var bCtrlKeyCode = oEvent.ctrlKey || oEvent.metaKey;
                if (nKeyCode == 82 && bCtrlKeyCode) {
                    //如果是Ctrl+R不阻止
                    //阻止触发默认的ctrl+R事件
                    oEvent.returnValue = true;
                }
                //如果是四个方向键 Crtl alt shift  直接返回true
                else if (nKeyCode == 37 || nKeyCode == 38 || nKeyCode== 39 || nKeyCode == 40 ||
                    nKeyCode == 16 || nKeyCode == 17 || nKeyCode == 18) {
                    oEvent.returnValue = true;
                } else if (!compareTwoString(contentAfterKeyup, contentBeforeKeydown)) {
                    // //selectedRange=ue.selection.getNative().getRangeAt(0);
                    // //selectedRange=selectedRange.cloneRange();
                    // ue.setContent(contentBeforeKeydownHtml);
                    ue.setContent(contentBeforeKeydownHtml, false, true);
                    // //ue.undoManger.list.pop();
                    // //ue.execCommand('undo');
                    // selectedRange2=ue.selection.getNative().getRangeAt(0);
                    // ue.selection.getNative().removeAllRanges();
                    // //ue.selection.getNative().getRangeAt(0).endOffset=1;
                    // ue.selection.getNative().addRange(selectedRange);
                    oEvent.returnValue = false;
                } else {
                    oEvent.returnValue = true;
                }


                //alert("1:"+contentBeforeKeydown+"\n"+"1:"+contentAfterKeyup);

                //ue.execCommand('undo');

            });

            UE.dom.domUtils.on(ue.body, "keydown", function (oEvent) {
                var oEvent = oEvent || window.oEvent;
                //获取键盘的keyCode值
                var nKeyCode = oEvent.keyCode || oEvent.which || oEvent.charCode;
                contentBeforeKeydown = ue.getContentTxt();
                contentBeforeKeydownHtml = ue.getContent();
                //alert(oEvent.keyCode);
                //只对输入是空格和backspace和四个方向键响应，其他的键盘输入一概不响应，而且是backspace时判断前面的字符是
                //空格还是字母，如果是空格让删除，如果不是空格就不让删除。
                // if(oEvent.keyCode==32||oEvent.keyCode==37||oEvent.keyCode==38||oEvent.keyCode==39||oEvent.keyCode==40||
                // oEvent.keyCode==16||oEvent.keyCode==17||oEvent.keyCode==18){
                //     oEvent.returnValue = true;
                // }
                // else if(oEvent.keyCode==8){
                //
                //     selectedRange=ue.selection.getNative().getRangeAt(0);
                //     if(selectedRange.collapsed){
                //         startNode=selectedRange.startContainer;
                //         if(startNode.nodeType==3){
                //
                //             backspaceChar=startNode.textContent.charAt(selectedRange.startOffset-1);
                //             konggeValue=backspaceChar.charCodeAt();
                //             if(konggeValue==32||konggeValue==160){
                //                 oEvent.returnValue=true;
                //             }
                //             else{
                //                 oEvent.returnValue=false;
                //             }
                //         }
                //         else{
                //             oEvent.returnValue=true;
                //         }
                //
                //     }
                //     else{
                //         oEvent.returnValue=true;
                //     }
                //
                // }
                // else{
                //     oEvent.returnValue = false;
                // }
                //
                // //alert(nKeyCode);
                // //var aNode=ue.selection.getStart();
                // //spanNode=UE.dom.domUtils.findParentByTagName(aNode, [ "span" ] );
                // //if(spanNode!=null&&spanNode.tagName=="SPAN"){
                // //ue.focus();
                // //ue.execCommand('inserthtml',oEvent.key);
                // //var txtNode = document.createTextNode(oEvent.key);
                // //UE.dom.domUtils.insertAfter(spanNode, txtNode);
                //
                // //}
                // //ue.selection.clearRange();
                // //ue.execCommand('removeformat');
                // //oEvent.returnValue = false;
            });
            //var doc=ue.selection.getRange().document;
            $(ue.body).on("click", "a", function (event) {
                //alert($(this).text());
                var parentNode = UE.dom.domUtils.findParentByTagName(this, ["span"]);
                UE.dom.domUtils.remove(this);
                //alert(parentNode.outerHTML);
                parentNode.outerHTML = parentNode.innerText;
                setRailwaySpecialWords(ue);
                //fire contentchange
                ue.fireEvent('contentchange');
            });
            //UE自带的on事件绑定不好用，改为使用jQuery的on事件绑定
            //UE.dom.domUtils.on(bt,"click",function(e){
            //e为事件对象，this为被点击元素对戏那个
            //alert(this.innerHTML);
            //var parentNode = UE.dom.domUtils.findParentByTagName(this, [ "span" ] );
            //UE.dom.domUtils.remove(this);
            //alert(parentNode.outerHTML);
            //parentNode.outerHTML=parentNode.innerText;
            //});
        });

    });
</script>
